package com.ljy.my_study.leetcode.回文对;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author lijunying
 * @date 2020/8/6 10:55
 */
public class TestMain {

//    给定一组唯一的单词， 找出所有不同 的索引对(i, j)，
//    使得列表中的两个单词， words[i] + words[j] ，可拼接成回文串。
//
//    示例 1:
//
//    输入: ["abcd","dcba","lls","s","sssll"]
//    输出: [[0,1],[1,0],[3,2],[2,4]]
//    解释: 可拼接成的回文串为 ["dcbaabcd","abcddcba","slls","llssssll"]
//    示例 2:
//
//    输入: ["bat","tab","cat"]
//    输出: [[0,1],[1,0]]
//    解释: 可拼接成的回文串为 ["battab","tabbat"]

    public static void main(String[] args) {
        String[] words={"abcd","dcba","lls","s","sssll"};
        System.out.println(new TestMain().palindromePairs(words));
    }

    public List<List<Integer>> palindromePairs(String[] words) {
        List<List<Integer>> result=new ArrayList<>();
        for(int i=0;i<words.length-1;i++){
            for(int j=i+1;j<words.length;j++){
                if(isPalindrome(words[i],words[j])){
                    result.add(Arrays.asList(i,j));
                }
                if(isPalindrome(words[j],words[i])){
                    result.add(Arrays.asList(j,i));
                }
            }
        }
        return result;
    }

    private boolean isPalindrome(String a,String b){
        char[] aChars=a.toCharArray();
        char[] bChars=b.toCharArray();
        int aLen=aChars.length;
        int bLen=bChars.length;
        int start=0;
        int end=aLen+bLen-1;
        while(start<=end){
            char c1;
            char c2;
            if(start<aLen){
                c1=aChars[start];
            }else{
                c1=bChars[start-aLen];
            }
            if(end<aLen){
                c2=aChars[end];
            }else{
                c2=bChars[end-aLen];
            }
            if(c1==c2){
                start++;
                end--;
                continue;
            }
            return false;
        }
        return true;

    }
}
